import random
import datetime
'''
RFC 2455: Internet Calendaring and Scheduling Core Object Specification (iCalendar)

'''

import lunardate
    
def _isMonthExist(year, month, leapMonth):
    try:
        lunardate.LunarDate(year, month, 1, leapMonth)
    except ValueError:
        return False
    return True

def _getDate(year, month, day, leapMonth, leapMonthWa, lastDayWa):
    try:
        return lunardate.LunarDate(year, month, day, leapMonth).toSolarDate()
    except ValueError:
        pass
    
    if _isMonthExist(year, month, leapMonth):
        if day == 30 and lastDayWa != 0:
            res = lunardate.LunarDate(year, month, 29, leapMonth).toSolarDate()
            if lastDayWa == 1:
                res += 1
            return res
        return None
    
    if leapMonth and leapMonthWa != 0:
        if leapMonthWa == -1:
            return _getDate(year, month, day, 0, 0, lastDayWa)
        else:
            if month == 12:
                return _getDate(year+1, 1, day, 0, 0, lastDayWa)
            else:
                return _getDate(year, month+1, day, 0, 0, lastDayWa)
    
    return None
        
    
def lunar2ics(month, day, leapMonth, beginYear, endYear, comment, leapMonthWa=0, lastDayWa=0):    
    res = []
    for i in range(beginYear, endYear):
        date = _getDate(i, month, day, leapMonth, leapMonthWa, lastDayWa)
        if date is not None:
            res.append(date)
    return solar2ics(res, comment)

def _yieldDate(year, month, day, leapMonth, leapMonthWa, lastDayWa):
    yield year, month, day, leapMonth
    if day == 30 and lastDayWa == -1:
        yield year, month, 29, leapMonth
    else:
        yield year, month, 29, leapMonth, 1
    
    if leapMonth and leapMonthWa == -1:
        yield year, month, day, 0
    if leapMonth and leapMonthWa == 1:
        if month != 12:
            yield year, month+1, day, 0
        else:
            yield year+1, month, day
    


def solar2ics(dates, comment):
    '''
    >>> import datetime
    >>> a = solar2ics([datetime.date(1900, 1, 1)], "mother's birthday")    
    '''
    res = []
    res.append('BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//LUNAR2ICS//NONSGML Version 1//EN\r\n')
    for x in dates:
        res.append(_date2vevent(x, comment))
    res.append('END:VCALENDAR\r\n')
    return ''.join(res)

def _date2vevent(date, summary):
    r'''
    >>> a = _date2vevent(datetime.date(1900, 1, 31), 'HELLO').splitlines()
    >>> print '\n'.join(a[:1] + a[2:])    
    BEGIN:VEVENT
    SUMMARY:HELLO
    DTSTART;VALUE=DATE:19000131
    DTEND;VALUE=DATE:19000201
    END:VEVENT
    >>>
    '''
    res = []
    res.append('BEGIN:VEVENT')
    res.append('UID:lunar2ics-%s' % random.random())
    if summary:
        res.append('SUMMARY:%s' % summary)
    res.append('DTSTART;VALUE=DATE:%04d%02d%02d' % (date.year, date.month, date.day))
    nextday = date + datetime.timedelta(days=1)
    res.append('DTEND;VALUE=DATE:%04d%02d%02d' % (nextday.year, nextday.month, nextday.day))
    res.append('END:VEVENT')
    res.append('')
    return '\r\n'.join(res)        
    

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    
    
    
    
        
